﻿using Dotnet.Utils.Utility.Config;
using Dotnet.Utils.Utility.EncryptUtil;
using Dotnet.Utils.Utility.ObjectExtensions.Obj;
using Dotnet.Utils.Utility.ObjectExtensions.Str;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dotnet.Utils.Utility.Other
{
    /*

    /// <summary>
    /// 页面地址工具
    /// </summary>
    /// <remarks>
    ///  对Url进行加密、解密处理，防止Url参数出错等， 默认分隔符号为“^”，可对分隔符号进行重写；
    ///  默认输出参数名为“PARAMETER”，可配置(new UrlUtil()).Parameter="ID";
    /// </remarks>
    /// <example>
    /// 1、单参数简单传输：
    /// <code>
    /// string sUrl= UrlUtil.DirectGetUrl(页面地址如("test.aspx"),参数名称如"ID",参数对应值如"123");
    /// Response.Redirect(sUrl);
    /// </code>
    /// 2、多参数简单传输：
    /// <code>
    /// UrlUtil curUrl = new UrlUtil();
    /// curUrl.AddParameter("ID","20");
    /// curUrl.AddParameter("CODE","40");
    /// string sUrl = curUrl.GetUrl(页面地址如("test.aspx"));
    /// Response.Redirect(sUrl);
    /// </code>
    /// 3、接收数据：
    /// <code>
    /// HashTable HT = (new UrlUtil()).GetParameter(Request);
    /// string sID = HT["ID"].ToString();
    /// string sCode = HT["CODE"].ToString();
    /// </code>
    /// </example>
    public class UrlParams
    {
        /// <summary>
        /// 默认参数名
        /// </summary>
        public const string PARAMETER = "PARAMETER";
        // 存储串
        private Hashtable paramters;

        /// <summary>
        /// 初始化<B>UrlUtil</B>类的新实例
        /// </summary>
        public UrlParams()
        {
        }
        public UrlParams(int curId)
            : this(curId, null, null)
        {
        }
        public UrlParams(string curType, string curCode)
            : this(NoneValue.NaInt, curType, curCode)
        {

        }
        public UrlParams(int curId, string curType, string curCode)
        {
            AddParameter("CurId", curId.ToString());
            if (curType != null)
            {
                AddParameter("CurType", curType);
            }
            if (curCode != null)
            {
                AddParameter("CurCode", curCode);
            }
        }
        /// <summary>
        /// 格式化当前Request中的参数对象
        /// </summary>
        /// <returns>参数对象</returns>
        public static UrlParams ParseCurRequest()
        {
            return Parse(HttpContext.Current.Request);
        }
        /// <summary>
        /// 格式化request中的参数对象
        /// </summary>
        /// <param name="request">指定的Request</param>
        /// <returns>参数对象</returns>
        public static UrlParams Parse(HttpRequest request)
        {
            UrlParams obj = new UrlParams();
            Hashtable hash = UrlParams.GetParameter(request);
            foreach (string sKey in hash.Keys)
            {
                obj.AddParameter(sKey, hash[sKey]);
            }
            return obj;
        }
        /// <summary>
        /// 返回默认的ID参数
        /// </summary>
        /// <param name="request"></param>
        /// <returns>CurId当前的请求参数</returns>
        public static int GetCurParamId(System.Web.HttpRequest request)
        {
            Hashtable hash = UrlParams.GetParameter(request);
            if (hash.ContainsKey("CurId"))
                return StringHelper.ParseInt((string)hash["CurId"], NoneValue.NaInt);
            return NoneValue.NaInt;
        }
        /// <summary>
        /// 返回内置定义的类型编码、值编码及ID参数
        /// </summary>
        /// <param name="request">当前请求</param>
        /// <param name="sCurType">CurType值</param>
        /// <param name="sCurCode">CurCode值</param>
        /// <returns>CurId值</returns>
        public static int GetCurParam(System.Web.HttpRequest request, out string sCurType, out string sCurCode)
        {
            sCurType = sCurCode = null;
            Hashtable hash = UrlParams.GetParameter(request);
            if (hash.ContainsKey("CurType"))
                sCurType = (string)hash["CurType"];
            if (hash.ContainsKey("CurCode"))
                sCurCode = (string)hash["CurCode"];
            if (hash.ContainsKey("CurId"))
                return StringHelper.ParseInt((string)hash["CurId"], NoneValue.NaInt);
            return NoneValue.NaInt;
        }
        public static string GetParam(string sParamName)
        {
            return GetParam(HttpContext.Current.Request, sParamName);
        }
        public static string GetParam(System.Web.HttpRequest request, string sParamName)
        {
            Hashtable hash = UrlParams.GetParameter(request);
            if (hash.ContainsKey(sParamName))
                return (string)hash[sParamName];
            return null;
        }

        /// <summary>
        /// 添加参数(参数名或参数值中不能包含字符"^")
        /// </summary>
        /// <param name="pName"><see cref="object"/>，参数名</param>
        /// <param name="oValue"><see cref="string"/>，参数值</param>
        /// <returns><see cref="bool"/>，是否添加成功</returns>
        public bool AddParameter(string pName, object oValue)
        {
            AddParameter(pName, oValue.ToString());
            return true;
        }
        /// <summary>
        /// 添加参数(参数名或参数值中不能包含字符"^")
        /// </summary>
        /// <param name="pName"><see cref="object"/>，参数名</param>
        /// <param name="pValue"><see cref="string"/>，参数值</param>
        /// <returns><see cref="bool"/>，是否添加成功</returns>
        public void AddParameter(string pName, string pValue)
        {
            if (paramters == null) paramters = new Hashtable();
            paramters[pName] = pValue;
        }

        /// <summary>
        /// 生成url地址
        /// </summary>
        /// <param name="sPageAddress"><see cref="string"/>，页面地址</param>
        /// <returns><see cref="string"/>，返回url地址</returns>
        public string GetUrl(string sPageAddress)
        {
            if (paramters == null) return sPageAddress;
            return string.Format("{0}{1}PARAMETER={2}", sPageAddress, sPageAddress.IndexOf("?") > 0 ? "&" : "?", EncodeParameters(paramters));
        }
        /// <summary>
        /// 加密参数
        /// </summary>
        /// <param name="pName">参数名</param>
        /// <param name="pValue">参数值</param>
        /// <returns></returns>
        public static string EncodeParameters(string pName, string pValue)
        {
            byte[] bytes = System.Text.ASCIIEncoding.UTF8.GetBytes(pName + "^" + pValue);
            string sEnCodeStr = Convert.ToBase64String(bytes);
            return CryptoUtil.UrlEncodeBase64String(sEnCodeStr);
        }
        /// <summary>
        /// 加密参数
        /// </summary>
        /// <param name="sNameValues">参数列表</param>
        /// <returns></returns>
        public static string EncodeParameters(IDictionary sNameValues)
        {
            string[] strs = new string[sNameValues.Count];
            int i = 0;
            foreach (object oKey in sNameValues.Keys)
            {
                strs[i++] = oKey.ToString() + "^" + sNameValues[oKey];
            }
            byte[] bytes = System.Text.ASCIIEncoding.UTF8.GetBytes(string.Join("^", strs));
            string sEnCodeStr = Convert.ToBase64String(bytes);
            return CryptoUtil.UrlEncodeBase64String(sEnCodeStr);
        }
        /// <summary>
        /// 解密参数
        /// </summary>
        /// <param name="sParameters">需要解密的参数字符串</param>
        /// <returns>参数哈希表</returns>
        public static Hashtable DecodeParameters(string sParameters)
        {
            Hashtable ht = new Hashtable();
            sParameters = CryptoUtil.UrlDecodeBase64String(sParameters);
            byte[] bytes = Convert.FromBase64String(sParameters);
            sParameters = System.Text.ASCIIEncoding.UTF8.GetString(bytes);
            string[] strs = sParameters.Split('^');
            int iLength = strs.Length;
            if (iLength > 1)
                for (int i = 0; i < iLength; i += 2)
                {
                    ht.Add(strs[i], strs[i + 1]);
                }
            return ht;
        }

        /// <summary>
        /// 直接生成Url
        /// </summary>
        /// <param name="sPageAddress"><see cref="string"/>，页面地址</param>
        /// <param name="pName"><see cref="string"/>，参数名称</param>
        /// <param name="pValue"><see cref="string"/>，参数值</param>
        /// <returns><see cref="string"/>，返回url地址</returns>
        public static string DirectGetUrl(string sPageAddress, string pName, string pValue)
        {
            byte[] bytes = System.Text.ASCIIEncoding.UTF8.GetBytes(pName + "^" + pValue);
            string sEnCodeStr = Convert.ToBase64String(bytes);
            sEnCodeStr = CryptoUtil.UrlEncodeBase64String(sEnCodeStr);

            return string.Format("{0}{1}PARAMETER={2}", sPageAddress, sPageAddress.IndexOf("?") > 0 ? "&" : "?", sEnCodeStr);
        }

        /// <summary>
        /// 生成访问Url地址
        /// </summary>
        /// <param name="request"><see cref="System.Web.HttpRequest"/>，http请求</param>
        /// <param name="sUserId"><see cref="string"/>，用户ID</param>
        /// <param name="sVisitPageAddress"><see cref="string"/>，要访问的页面地址</param>
        /// <returns><see cref="string"/>，返回url地址</returns>
        /// <remarks>
        /// 获取可以直接访问的url地址，用于发邮件给用户时给出链接地址，用户可以直接点击链接地址即可访问此页面
        /// </remarks>
        public string GetInstantVisitUrl(HttpRequest request, string sUserId, string sVisitPageAddress)
        {
            this.AddParameter("UserId", sUserId);
            //this.AddParameter("Password", sPassword);
            this.AddParameter("VisitPage", sVisitPageAddress);
            return this.GetUrl("http://" + request.Url.Authority + request.ApplicationPath + "/WebTools/TransferPage.aspx");
        }

        /// <summary>
        /// 生成访问Url地址
        /// </summary>
        /// <param name="sUserId"><see cref="string"/>，用户ID</param>
        /// <param name="sVisitPageAddress"><see cref="string"/>，要访问的页面地址</param>
        /// <returns><see cref="string"/>，返回url地址</returns>
        /// <remarks>
        /// 获取可以直接访问的url地址，用于发邮件给用户时给出链接地址，用户可以直接点击链接地址即可访问此页面
        /// </remarks>
        public string GetInstantVisitUrl(string sUserId, string sVisitPageAddress)
        {
            this.AddParameter("UserId", sUserId);
            this.AddParameter("VisitPage", sVisitPageAddress);
            string sUrl = SysConfigUtil.GetAppConfig("ApplicationUrl");
            if (sUrl == null)
                sUrl = "http://localhost/InsSystemApp";
            return this.GetUrl(sUrl + "/WebTools/TransferPage.aspx");
        }

        /// <summary>
        /// 获取参数的散列表
        /// </summary>
        /// <param name="Request"><see cref="System.Web.HttpRequest"/>，http请求</param>
        /// <returns><see cref="System.Collections.Hashtable"/>，返回散列表</returns>
        public static Hashtable GetParameter(System.Web.HttpRequest Request)
        {
            return GetParameter(Request[PARAMETER]);
        }
        /// <summary>
        /// 获取参数的散列表
        /// </summary>
        /// <returns><see cref="System.Collections.Hashtable"/>，返回散列表</returns>
        public Hashtable GetCurrentParameter()
        {
            return GetParameter(HttpContext.Current.Request);
        }
        /// <summary>
        /// 获取解密后的参数集合
        /// </summary>
        /// <param name="sParameters"><see cref="string"/>，加密后的字串</param>
        /// <returns><see cref="System.Collections.Hashtable"/>，参数集合</returns>
        public static Hashtable GetParameter(string sParameters)
        {
            Hashtable ht = new Hashtable();
            if (sParameters != null)
            {
                sParameters = CryptoUtil.UrlDecodeBase64String(sParameters);
                try
                {
                    byte[] bytes = Convert.FromBase64String(sParameters);
                    sParameters = System.Text.ASCIIEncoding.UTF8.GetString(bytes);
                    string[] strs = sParameters.Split('^');
                    int iLength = strs.Length;
                    for (int i = 0; i < iLength; i += 2)
                    {
                        ht.Add(strs[i], strs[i + 1]);
                    }
                }
                catch
                {
                }
            }
            return ht;
        }
    }

    #region UrlPartGenerator
    /// <summary>
    /// 指定参数值产生方式
    /// </summary>
    public enum 参数值产生方式
    {
        /// <summary>
        /// 指定数据的方式
        /// </summary>
        指定数据 = 1,
        /// <summary>
        /// 从URL中提取的方式
        /// </summary>
        从URL中提取 = 2
    }

    /// <summary>
    /// Url参数
    /// </summary>
    public class UrlPart
    {
        private string sKey;
        private string sValue;
        private 参数值产生方式 type;
        /// <summary>
        /// 关键字
        /// </summary>
        public string Key
        {
            get { return sKey; }
            set { sKey = value; }
        }
        /// <summary>
        /// 值
        /// </summary>
        public string Value
        {
            get { return sValue; }
            set { sValue = value; }
        }
        /// <summary>
        /// 参数值产生方式
        /// </summary>
        public 参数值产生方式 Type
        {
            get { return type; }
            set { type = value; }
        }
        /// <summary>
        /// 初始化<B>UrlPart</B>类的新实例
        /// </summary>
        /// <param name="sKey"><see cref="string"/>，关键字</param>
        /// <param name="sValue"><see cref="string"/>，值</param>
        /// <param name="type"><see cref="参数值产生方式"/></param>
        public UrlPart(string sKey, string sValue, 参数值产生方式 type)
        {
            this.sKey = sKey;
            this.sValue = sValue;
            this.type = type;
        }
    }

    /// <summary>
    /// 提取url参数片断
    /// </summary>
    public class UrlPartGenerator
    {
        private ArrayList parts = new ArrayList();
        private System.Web.UI.Page curPage;

        /// <summary>
        /// 初始化<b>UrlPartGenerator</b>类的新实例
        /// </summary>
        /// <param name="p"><see cref="System.Web.UI.Page"/>，页面</param>
        public UrlPartGenerator(System.Web.UI.Page p)
        {
            this.curPage = p;
        }

        /// <summary>
        /// 添加Url参数
        /// </summary>
        /// <param name="urlPart"><see cref="UrlPart"/>，Url参数</param>
        /// <returns><see cref="bool"/>，返回是否添加成功</returns>
        public bool AddUrlPart(UrlPart urlPart)
        {
            if (urlPart.Key == null
                || urlPart.Key.Trim().Length == 0
                || (urlPart.Type == 参数值产生方式.指定数据 && (urlPart.Value == null || urlPart.Value.Trim().Length == 0))
                || parts.Contains(urlPart))
            {
                return false;
            }
            else
            {
                parts.Add(urlPart);
                return true;
            }
        }

        /// <summary>
        /// 添加Url参数
        /// </summary>
        /// <param name="sKey"><see cref="string"/>，关键字</param>
        /// <param name="sValue"><see cref="string"/>，值</param>
        /// <param name="type"><see cref="参数值产生方式"/></param>
        /// <returns><see cref="bool"/>，返回是否添加成功</returns>
        public bool AddUrlPart(string sKey, string sValue, 参数值产生方式 type)
        {
            UrlPart urlPart = new UrlPart(sKey, sValue, type);
            return this.AddUrlPart(urlPart);
        }

        /// <summary>
        /// 生成结果
        /// </summary>
        /// <returns><see cref="string"/>，返回结果串</returns>
        public string GenerateResult()
        {
            if (curPage == null || parts.Count == 0)
                return string.Empty;
            StringBuilder temp = new StringBuilder();
            foreach (UrlPart urlPart in parts)
            {
                if (urlPart.Type == 参数值产生方式.指定数据)
                {
                    temp.Append("&" + urlPart.Key.Trim() + "=" + urlPart.Value.Trim());
                }
                else if (curPage.Request[urlPart.Key.Trim()] != null)
                {
                    temp.Append("&" + urlPart.Key.Trim() + "=" + curPage.Request[urlPart.Key.Trim()]);
                }
            }
            string result = temp.ToString();
            if (result.Length > 0)
                result = result.Substring(1);
            return result;
        }
    }
    #endregion
    */
}
